package com.hn.common.utils;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.hn.common.utils.spring.SpringUtils;
import com.hn.project.common.domain.database.SysDictData;
import com.hn.project.common.service.SysDictDataService;

import java.lang.reflect.Field;
import java.util.List;

public class SysDictDataConverter implements Converter<Integer> {

	@Override
	public Class<Integer> supportJavaTypeKey() {
		return Integer.class;
	}

	@Override
	public CellDataTypeEnum supportExcelTypeKey() {
		return CellDataTypeEnum.STRING;
	}

	@Override
	public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
                                     GlobalConfiguration globalConfiguration) {
		String stringValue = cellData.getStringValue();
		Field field = contentProperty.getField();
		ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
		String format = excelProperty.format();
		SysDictDataService dictTypeService = SpringUtils.getBean(SysDictDataService.class);
		List<SysDictData> dictDatas = dictTypeService.listSysDictData(format);
		String dictVal = "";
		for (SysDictData sysDictData : dictDatas) {
			if(sysDictData.getDictLabel().equals(stringValue)){
				dictVal = sysDictData.getDictValue();
			}
		}
		return Integer.valueOf(dictVal);
	}

	@Override
	public CellData<String> convertToExcelData(Integer value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
		Field field = contentProperty.getField();
		ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
		String format = excelProperty.format();
		SysDictDataService dictTypeService = SpringUtils.getBean(SysDictDataService.class);
		List<SysDictData> sysDictDatas = dictTypeService.listSysDictData(format);
		String dictLabel = "";
		for (SysDictData sysDictData : sysDictDatas) {
			if(value.equals(Integer.valueOf(sysDictData.getDictValue()))){
				dictLabel = sysDictData.getDictLabel();
			}
		}
		return new CellData<>(dictLabel);
	}

}
